"""
客户服务
"""
from flask_login import current_user
from datetime import datetime
from app.models import Customer, Contact, FollowUp, User, Region, get_db
from app.models.message import MessageRecipient
from app.services.message_service import MessageService

class CustomerService:
    """客户服务类"""
    
    @staticmethod
    def get_customers(page=1, per_page=10):
        """获取客户列表"""
        db = get_db()
        customers = Customer.query.filter_by(manager_id=current_user.id).paginate(
            page=page, per_page=per_page, error_out=False)
        return customers
    
    @staticmethod
    def get_customer(customer_id):
        """获取单个客户"""
        db = get_db()
        customer = Customer.query.get_or_404(customer_id)
        
        # 检查权限 - 允许客户负责人和管理员访问
        if current_user.role == 'sales' and customer.manager_id != current_user.id:
            return None
        
        return customer
    
    @staticmethod
    def create_customer(name, category, category_other, location, location_other, source, source_other, 
                       province_id, city_id, district_id, address, manager_id):
        """创建客户"""
        db = get_db()
        
        # 生成客户编号
        customer_number = Customer.generate_customer_number()
        
        # 处理客户分类
        final_category = category
        if category == '其他' and category_other:
            final_category = category_other
        
        # 处理客户归属地
        final_location = location
        if location == '其他' and location_other:
            final_location = location_other
        
        # 处理客户来源
        final_source = source
        if source == '其他' and source_other:
            final_source = source_other
        
        customer = Customer(
            name=name,
            customer_number=customer_number,
            category=final_category,
            category_other=category_other if category == '其他' else None,
            location=final_location,
            location_other=location_other if location == '其他' else None,
            source=final_source,
            source_other=source_other if source == '其他' else None,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            address=address,
            manager_id=manager_id or current_user.id
        )
        
        db.session.add(customer)
        db.session.commit()
        
        # 发送消息通知
        try:
            # 获取管理员和销售部门领导ID列表
            admin_ids = MessageService.get_admin_ids()
            sales_leader_ids = MessageService.get_sales_leader_ids()
            
            # 合并收件人ID列表
            recipient_ids = list(set(admin_ids + sales_leader_ids))
            
            print(f"客户创建消息调试 - 管理员IDs: {admin_ids}, 销售领导IDs: {sales_leader_ids}, 收件人IDs: {recipient_ids}")
            
            if recipient_ids:
                # 准备消息变量
                variables = {
                    'customer_name': name,
                    'customer_phone': '',  # 客户电话暂时为空，后续可以添加
                    'creator_name': current_user.name or '未知用户'
                }
                
                print(f"客户创建消息调试 - 发送消息给 {len(recipient_ids)} 个接收者")
                
                # 由于数据库要求receiver_id非空，使用第一个接收者作为receiver_id
                primary_receiver_id = recipient_ids[0] if recipient_ids else None
                
                if len(recipient_ids) == 1:
                    # 单个接收者，直接发送消息
                    message = MessageService.create_message(
                        title='新客户添加',
                        content=f"用户 {current_user.name or '未知用户'} 添加了新客户 {name}，联系方式: {variables.get('customer_phone', '')}",
                        message_type='通知',
                        sender_id=current_user.id,
                        receiver_id=primary_receiver_id,  # 指定接收者
                        target_type='customer',
                        target_id=customer.id
                    )
                else:
                    # 多个接收者，使用群发消息，但指定主接收者
                    message = MessageService.create_bulk_message(
                        title='新客户添加',
                        content=f"用户 {current_user.name or '未知用户'} 添加了新客户 {name}，联系方式: {variables.get('customer_phone', '')}",
                        message_type='通知',
                        sender_id=current_user.id,
                        recipient_ids=recipient_ids,
                        target_type='customer',
                        target_id=customer.id
                    )
                
                print(f"客户创建消息调试 - 消息发送成功，消息ID: {message.id}")
                
                # 验证接收者记录
                recipients = MessageRecipient.query.filter_by(message_id=message.id).all()
                print(f"客户创建消息调试 - 群发消息，接收者数量: {len(recipients)}, 接收者IDs: {[r.user_id for r in recipients]}")
                    
        except Exception as e:
            # 记录错误但不影响客户创建
            print(f"发送客户创建通知失败: {str(e)}")
            import traceback
            traceback.print_exc()
        
        return True, "客户创建成功", customer
    
    @staticmethod
    def update_customer(customer_id, name, category, category_other, location, location_other, source, source_other, 
                       province_id, city_id, district_id, address, manager_id):
        """更新客户"""
        db = get_db()
        customer = Customer.query.get_or_404(customer_id)
        
        # 检查权限
        if customer.manager_id != current_user.id:
            return False, "无权限修改此客户"
        
        # 处理客户分类
        final_category = category
        if category == '其他' and category_other:
            final_category = category_other
        
        # 处理客户归属地
        final_location = location
        if location == '其他' and location_other:
            final_location = location_other
        
        # 处理客户来源
        final_source = source
        if source == '其他' and source_other:
            final_source = source_other
        
        customer.name = name
        customer.category = final_category
        customer.category_other = category_other if category == '其他' else None
        customer.location = final_location
        customer.location_other = location_other if location == '其他' else None
        customer.source = final_source
        customer.source_other = source_other if source == '其他' else None
        customer.province_id = province_id
        customer.city_id = city_id
        customer.district_id = district_id
        customer.address = address
        customer.manager_id = manager_id or current_user.id
        
        db.session.commit()
        
        return True, "客户信息更新成功"
    
    @staticmethod
    def delete_customer(customer_id):
        """删除客户"""
        db = get_db()
        customer = Customer.query.get_or_404(customer_id)
        
        # 检查权限
        if customer.manager_id != current_user.id:
            return False, "无权限删除此客户"
        
        db.session.delete(customer)
        db.session.commit()
        
        return True, "客户删除成功"
    
    @staticmethod
    def create_contact(customer_id, name, position, phone, email, is_primary=False):
        """创建客户联系人"""
        db = get_db()
        customer = Customer.query.get_or_404(customer_id)
        
        # 检查权限
        if customer.manager_id != current_user.id:
            return False, "无权限为此客户创建联系人"
        
        contact = Contact(
            customer_id=customer_id,
            name=name,
            position=position,
            phone=phone,
            email=email,
            is_primary=is_primary
        )
        
        db.session.add(contact)
        db.session.commit()
        
        return True, "联系人创建成功", contact
    
    @staticmethod
    def get_customer_contacts(customer_id):
        """获取客户联系人列表"""
        db = get_db()
        customer = Customer.query.get_or_404(customer_id)
        
        # 检查权限 - 允许客户负责人和管理员访问
        if current_user.role == 'sales' and customer.manager_id != current_user.id:
            return None
        
        contacts = Contact.query.filter_by(customer_id=customer_id).all()
        return contacts
    
    @staticmethod
    def get_contact(contact_id):
        """获取单个联系人"""
        db = get_db()
        contact = Contact.query.get_or_404(contact_id)
        customer = Customer.query.get_or_404(contact.customer_id)
        
        # 检查权限
        if customer.manager_id != current_user.id:
            return None
        
        return contact
    
    @staticmethod
    def update_contact(contact_id, name, position, phone, email, is_primary=False):
        """更新联系人信息"""
        db = get_db()
        contact = Contact.query.get_or_404(contact_id)
        customer = Customer.query.get_or_404(contact.customer_id)
        
        # 检查权限
        if customer.manager_id != current_user.id:
            return False, "无权限修改此联系人"
        
        contact.name = name
        contact.position = position
        contact.phone = phone
        contact.email = email
        contact.is_primary = is_primary
        
        db.session.commit()
        
        return True, "联系人信息更新成功"
    
    @staticmethod
    def create_follow_up(customer_id, method, content, result, next_followup_time=None):
        """创建跟进记录"""
        db = get_db()
        customer = Customer.query.get_or_404(customer_id)
        
        # 检查权限
        if customer.manager_id != current_user.id:
            return False, "无权限为此客户创建跟进记录"
        
        follow_up = FollowUp(
            customer_id=customer_id,
            method=method,
            content=content,
            result=result,
            next_followup_time=datetime.strptime(next_followup_time, '%Y-%m-%d %H:%M:%S') if next_followup_time else None,
            manager_id=current_user.id
        )
        
        db.session.add(follow_up)
        db.session.commit()
        
        return True, "跟进记录创建成功", follow_up
    
    @staticmethod
    def get_sources():
        """获取客户来源列表"""
        return [
            ('网站', '网站'),
            ('推荐', '推荐'),
            ('展会', '展会'),
            ('电话', '电话'),
            ('其他', '其他')
        ]
    
    @staticmethod
    def get_categories():
        """获取客户分类列表"""
        return [
            ('普通客户', '普通客户'),
            ('VIP客户', 'VIP客户'),
            ('合作伙伴', '合作伙伴'),
            ('其他', '其他')
        ]
    
    @staticmethod
    def get_locations():
        """获取客户归属地列表"""
        return [
            ('山西区域', '山西区域'),
            ('四川区域', '四川区域'),
            ('新疆区域', '新疆区域'),
            ('安徽区域', '安徽区域'),
            ('山东区域', '山东区域'),
            ('湖北区域', '湖北区域'),
            ('福建区域', '福建区域'),
            ('北京区域', '北京区域'),
            ('重庆区域', '重庆区域'),
            ('云南区域', '云南区域'),
            ('其他', '其他')
        ]
    
    @staticmethod
    def get_provinces():
        """获取省份列表"""
        db = get_db()
        # 查询level为省、直辖市、自治区的记录
        provinces = Region.query.filter(
            Region.level.in_(['省', '直辖市', '自治区', '特别行政区'])
        ).order_by(Region.code).all()
        return [(p.id, p.name) for p in provinces]
    
    @staticmethod
    def get_cities(province_id):
        """获取指定省份的城市列表"""
        db = get_db()
        # 查询level为市、地区、自治州的记录
        cities = Region.query.filter(
            Region.level.in_(['市', '地区', '自治州', '盟']),
            Region.parent_id == province_id
        ).order_by(Region.code).all()
        return [(c.id, c.name) for c in cities]
    
    @staticmethod
    def get_districts(city_id):
        """获取指定城市的区县列表"""
        db = get_db()
        # 查询level为区、县、县级市的记录
        districts = Region.query.filter(
            Region.level.in_(['区', '县', '县级市', '旗', '自治县', '林区', '特区']),
            Region.parent_id == city_id
        ).order_by(Region.code).all()
        return [(d.id, d.name) for d in districts]
    
    @staticmethod
    def get_users():
        """获取用户列表，用于负责人选择"""
        db = get_db()
        users = User.query.filter_by(is_active=True).order_by(User.username).all()
        return [(u.id, u.username) for u in users]
    
    @staticmethod
    def get_customer_count():
        """获取客户总数"""
        db = get_db()
        return Customer.query.filter_by(manager_id=current_user.id).count()
    
    @staticmethod
    def get_customer_stats():
        """获取客户统计信息"""
        db = get_db()
        
        # 总客户数
        total = Customer.query.filter_by(manager_id=current_user.id).count()
        
        # 按客户分类统计
        category_stats = {}
        categories = ['普通客户', 'VIP客户', '合作伙伴', '其他']
        for category in categories:
            count = Customer.query.filter_by(manager_id=current_user.id, category=category).count()
            category_stats[category] = count
        
        # 按客户归属地统计
        location_stats = {}
        locations = ['山西区域', '四川区域', '新疆区域', '安徽区域', '山东区域', '湖北区域', '福建区域', '北京区域', '重庆区域', '云南区域', '其他']
        for location in locations:
            count = Customer.query.filter_by(manager_id=current_user.id, location=location).count()
            location_stats[location] = count
        
        # 按客户来源统计
        source_stats = {}
        sources = ['网站', '推荐', '展会', '电话', '其他']
        for source in sources:
            count = Customer.query.filter_by(manager_id=current_user.id, source=source).count()
            source_stats[source] = count
        
        return {
            'total': total,
            'category_stats': category_stats,
            'location_stats': location_stats,
            'source_stats': source_stats
        }
    
    @staticmethod
    def get_customer_follow_ups(customer_id):
        """获取客户跟进记录"""
        db = get_db()
        customer = Customer.query.get_or_404(customer_id)
        
        # 检查权限
        if customer.manager_id != current_user.id:
            return None
        
        follow_ups = FollowUp.query.filter_by(customer_id=customer_id).order_by(FollowUp.created_at.desc()).all()
        return follow_ups
    
    @staticmethod
    def get_follow_up(followup_id):
        """获取单个跟进记录"""
        db = get_db()
        follow_up = FollowUp.query.get_or_404(followup_id)
        customer = Customer.query.get_or_404(follow_up.customer_id)
        
        # 检查权限
        if customer.manager_id != current_user.id:
            return None
        
        return follow_up
    
    @staticmethod
    def update_follow_up(followup_id, method, content, result, next_followup_time=None):
        """更新跟进记录"""
        db = get_db()
        follow_up = FollowUp.query.get_or_404(followup_id)
        customer = Customer.query.get_or_404(follow_up.customer_id)
        
        # 检查权限
        if customer.manager_id != current_user.id:
            return False, "无权限修改此跟进记录"
        
        follow_up.method = method
        follow_up.content = content
        follow_up.result = result
        follow_up.next_followup_time = datetime.strptime(next_followup_time, '%Y-%m-%d %H:%M:%S') if next_followup_time else None
        
        db.session.commit()
        
        return True, "跟进记录更新成功"
    
    @staticmethod
    def search_customers(query, manager_id=None):
        """搜索客户"""
        db = get_db()
        if manager_id is None:
            manager_id = current_user.id
            
        customers = Customer.query.filter(
            Customer.manager_id == manager_id,
            db.or_(
                Customer.name.contains(query),
                Customer.customer_number.contains(query),
                Customer.category.contains(query),
                Customer.category_other.contains(query),
                Customer.location.contains(query),
                Customer.source.contains(query),
                Customer.source_other.contains(query),
                Customer.address.contains(query)
            )
        ).all()
        
        return customers